//
//  SignInViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/8/22.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import AFNetworking

class SignInViewController: SignViewController {
    
    fileprivate var headView : SignHeadView! //头部视图
    
    fileprivate let midView = UIView() //中间模块
    
    fileprivate let accountView = InputView.init(inputStyle: .account) //账号输入框
    fileprivate let passwordView = InputView.init(inputStyle: .password) //密码输入框
    
    fileprivate var phoneView = InputView.init(inputStyle: .phone) //手机号码
    fileprivate var codeView = InputView.init(inputStyle: .code) //验证码
    
    fileprivate let forgetBtn = UIButton() //忘记密码
    fileprivate let signInStyleBtn = UIButton() //登录类型
    fileprivate let signInBtn = UIButton() //登录

    override func viewDidLoad() {
        super.viewDidLoad()

        addSubView()
        addRightButton()
    }
    
    
    
    //MARK: 添加子视图
    fileprivate func addSubView() {
        
        headView = SignHeadView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 280)))
        self.view.addSubview(headView)
        
        forgetBtn.setTitle(forgetPassword, for: .normal)
        forgetBtn.setTitleColor(UIColor.black, for: .normal)
        forgetBtn.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 15))
        forgetBtn.addTarget(self, action: #selector(forgetPasswordAction), for: .touchUpInside)
        
        signInStyleBtn.setTitle(codeSignIn, for: .normal)
        signInStyleBtn.setTitleColor(UIColor.black, for: .normal)
        signInStyleBtn.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 15))
        signInStyleBtn.addTarget(self, action: #selector(selectSignInType(sender:)), for: .touchUpInside)
        
        signInBtn.setTitle(signIn_title, for: .normal)
        signInBtn.setTitleColor(UIColor.white, for: .normal)
        signInBtn.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 15))
        signInBtn.backgroundColor = UIColor.lightGray
        signInBtn.layer.cornerRadius = RATIO_H(maxNum: 20)
        signInBtn.layer.masksToBounds = true
        signInBtn.isEnabled = false
        signInBtn.addTarget(self, action: #selector(signInAction(sender:)), for: .touchUpInside)
        
        self.view.addSubview(forgetBtn)
        self.view.addSubview(signInStyleBtn)
        self.view.addSubview(signInBtn)
        
        self.view.addSubview(midView)
        
        accountView.textDelegate = self
        passwordView.textDelegate = self
        phoneView.textDelegate = self
        codeView.textDelegate = self
        
        passwordView.textField.isSecureTextEntry = true //密码不可见
        
        midView.addSubview(accountView)
        midView.addSubview(passwordView)
        midView.addSubview(phoneView)
        midView.addSubview(codeView)

        midView.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.equalToSuperview()
            make.width.equalTo(ScreenW * 2)
            make.height.equalTo(RATIO_H(maxNum: 120))
        }
        
        accountView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.equalToSuperview()
            make.width.equalTo(ScreenW)
            make.height.equalTo(RATIO_H(maxNum: 50))
        }
        
        passwordView.snp.makeConstraints { (make) in
            make.top.equalTo(accountView.snp.bottom).offset(RATIO_H(maxNum: 20))
            make.left.equalToSuperview()
            make.width.equalTo(accountView)
            make.height.equalTo(accountView)
        }
        
        phoneView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.equalTo(ScreenW)
            make.right.equalToSuperview()
            make.height.equalTo(passwordView)
        }
        
        codeView.snp.makeConstraints { (make) in
            make.top.equalTo(passwordView)
            make.left.equalTo(phoneView)
            make.right.equalTo(phoneView)
            make.height.equalTo(phoneView)
        }
        
        forgetBtn.snp.makeConstraints { (make) in
            make.top.equalTo(midView.snp.bottom).offset(RATIO_H(maxNum: 30))
            make.left.equalToSuperview().offset(RATIO(maxNum: 20))
            make.width.greaterThanOrEqualTo(10)
            make.height.equalTo(RATIO_H(maxNum: 20))
        }
        
        signInStyleBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(forgetBtn)
            make.right.equalToSuperview().offset(RATIO(maxNum: -20))
            make.width.greaterThanOrEqualTo(10)
            make.height.equalTo(forgetBtn)
        }
        
        signInBtn.snp.makeConstraints { (make) in
            make.top.equalTo(forgetBtn.snp.bottom).offset(RATIO_H(maxNum: 50))
            make.centerX.equalToSuperview()
            make.width.equalTo(RATIO(maxNum: 300))
            make.height.equalTo(RATIO_H(maxNum: 40))
        }
    }
    
    //MARK: 添加注册按钮
    fileprivate func addRightButton() {
        
        let rightItem = UIBarButtonItem.init(title: "注册", style: .done, target: self, action: #selector(signUpAction))
        self.navigationItem.rightBarButtonItem = rightItem
    }
    
    //MARK: 注册
    @objc fileprivate func signUpAction() {
        
        self.navigationController?.pushViewController(SignUpViewController(), animated: true)
    }
    
    //MARK: 忘记密码
    @objc fileprivate func forgetPasswordAction() {
        
        self.navigationController?.pushViewController(PasswordViewController(), animated: true)
    }
    
    //MARK: 选择登录方式
    @objc fileprivate func selectSignInType(sender:UIButton) {
        
        //验证码登录
        if sender.titleLabel?.text == codeSignIn {
            sender.setTitle(accountSignIn, for: .normal)
            forgetBtn.isHidden = true
            
            self.midView.snp.remakeConstraints { (make) in
                make.top.equalTo(self.headView.snp.bottom)
                make.width.equalTo(ScreenW * 2)
                make.left.equalTo(-ScreenW)
                make.height.equalTo(RATIO_H(maxNum: 120))
            }
            
        //账号密码
        }else{
            sender.setTitle(codeSignIn, for: .normal)
            forgetBtn.isHidden = false
            
            self.midView.snp.remakeConstraints { (make) in
                make.top.equalTo(headView.snp.bottom)
                make.left.equalToSuperview()
                make.width.equalTo(ScreenW * 2)
                make.height.equalTo(RATIO_H(maxNum: 120))
            }

            
        }
        
        self.monitorText()
        
    }
    
    //MARK: 登录
    @objc fileprivate func signInAction(sender:UIButton) {
        
        if sender.backgroundColor != UIColor.red {
            return
        }
        
        var parameters = [String:String]()
        var urlString = ""
        
        if signInStyleBtn.titleLabel?.text == codeSignIn {
            
            KMTool.waiting()
            //注意:此处服务器返回的不是json数据
            parameters = ["user_name":accountView.text,"password":passwordView.text]
            KMTool.requestData(URLString: url_signIn, parameters: parameters) { (string) in
                
                KMTool.stop()
                if string == "0" {
                    KMTool.getUserNews(userName: self.accountView.text, success: {
                        KMTool.setObject(self.accountView.text, forEnumKey: .phone)
                        self.navigationController?.popToRootViewController(animated: true)
                    })
                    
                }else{
                    KMTool.showText(_text: failToSignIn)
                }
            }
            
            
        }else{
            parameters = ["phone":phoneView.text,"verify":codeView.text]
            urlString = url_codeSignIn
            
            KMTool.waiting()
            KMTool.requestData(URLString: urlString, parameters: parameters) { (string) in
                KMTool.stop()
                
                if string == "\r\n/mobile/set_password"{
                    self.navigationController?.pushViewController(SetPasswordViewController.init(phoneNumber: self.phoneView.text), animated: true)
                }else if string == "\r\n/mobile/personal"{
                    KMTool.getUserNews(userName: self.phoneView.text, success: {
                        KMTool.setObject(self.phoneView.text, forEnumKey: .phone)
                        self.navigationController?.popToRootViewController(animated: true)
                    })
                }else if string == "\r\n0" {
                    KMTool.showText(_text: codeError)
                }
            }
        }
        
        
        
        
        
    }
    
    deinit {
        
        codeView.clearTimer()
    }

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}

extension SignInViewController : TextDelegate {
    
    //MARK: 监听文本
    func monitorText() {
        
        if signInStyleBtn.titleLabel?.text == codeSignIn {
            if accountView.text != "" && passwordView.text != "" {
                signInBtn.backgroundColor = UIColor.red
                signInBtn.isEnabled = true
            }else{
                signInBtn.backgroundColor = UIColor.lightGray
                signInBtn.isEnabled = false
            }
        }else{
            if phoneView.text != "" && codeView.text != "" {
                signInBtn.backgroundColor = UIColor.red
                signInBtn.isEnabled = true
            }else{
                signInBtn.backgroundColor = UIColor.lightGray
                signInBtn.isEnabled = false
            }
        }
        
    }
    
    //MARK: 获取验证码
    func getPhoneCode() {
        
        if phoneView.text == "" {
            KMTool.showText(_text: inputPhone)
            return
        }
        
        KMTool.waiting()
        KMTool.requestMethod(.post, URLString: url_signInCode, parameters: ["user_name":phoneView.text], success: { (value, json) in
            KMTool.stop()
            self.codeView.codeBlock!((json.dictionaryObject)!)//根据发送验证码情况做相应处理
        }) {
            KMTool.stop()
        }
    }
    
}
